#include "server.h"
friend_list *peoplelist;
void TCP_Process(void)
{
    int server_fd, client_fd, epoll_fd, nfds;
    struct sockaddr_in addr;

    struct epoll_event ev, events[MAX_EVENTS];

    // 创建 TCP 服务器
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("192.168.10.234");
    addr.sin_port = htons(PORT);

    if (bind(server_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
    {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    if (listen(server_fd, 10) == -1)
    {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    // 创建 epoll 实例
    if ((epoll_fd = epoll_create1(0)) == -1)
    {
        perror("epoll_create1");
        exit(EXIT_FAILURE);
    }

    // 添加服务器套接字到 epoll 实例中
    ev.events = EPOLLIN;
    ev.data.fd = server_fd;
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_fd, &ev) == -1)
    {
        perror("epoll_ctl: server_fd");
        exit(EXIT_FAILURE);
    }

    printf("服务器已经启动，端口号为:%d\n", PORT);
    








    pthread_mutex_init(&lock , NULL); 

    TCP_info convert[ONLINE]; //  转发包
    memset(convert, 0, sizeof(convert));
    //进行初始化
    for (size_t i = 0; i < ONLINE; i++)
    {
        convert[i].star_fd = -1;
    }
    peoplelist = fri_init_list();
    friend_f_Scanf(peoplelist);
    friend_Print(peoplelist);
    printf("好友列表加载成功\n");
    user_t dest_user;
    while (1)
    {
        nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);  //等待接收事件
        if (nfds == -1)
        {
            perror("epoll_wait");
            exit(EXIT_FAILURE);
        }

        for (int i = 0; i < nfds; i++)    // 循环处理事件
        {
            if (events[i].data.fd == server_fd)
            {
                // 接受新的连接
                if ((client_fd = accept(server_fd, NULL, NULL)) == -1)
                {
                    perror("accept");
                    exit(EXIT_FAILURE);
                }

                printf("有新的客户端连接:|%d|\n", client_fd);

                // 将新的客户端套接字添加到 epoll 实例中
                ev.events = EPOLLIN;
                ev.data.fd = client_fd;
                if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_fd, &ev) == -1)
                {
                    perror("epoll_ctl: client_fd");
                    exit(EXIT_FAILURE);
                }
                for (size_t k = 0; k < ONLINE; k++)
                {
                    if (convert[k].star_fd == -1)
                    {
                        convert[k].star_fd = client_fd; // 接收一个新的客户端的通信符   存储在第k个转化元素中
                        printf("\n\n\n=================================================\n");
                        printf("<<<k=|%ld|  client_fd=|%d|>>>\n", k, client_fd); // 打印
                        printf("=================================================\n\n\n\n");
                        break;
                    }
                }
            }
            else
            {
                // 处理客户端的数据   
                TCP_data datapack;   //TCP数据包  
                memset(&datapack, 0, sizeof(datapack));
                int bytes_received = recv(events[i].data.fd, &datapack, sizeof(datapack), 0);   //接收数据内容

                if (bytes_received <= 0)
                {
                    // 客户端关闭连接或发生错误
                    epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, NULL);
                    close(events[i].data.fd);
                    for (size_t num = 0; num < ONLINE; num++)
                    {
                        if (convert[num].star_fd ==  events[i].data.fd )
                        {
                            convert[num].star_fd  = -1;
                            break;
                        }
                        
                    }

                    printf("Connection closed\n");
                }
                else
                {

                    

                    // 打印接收到的数据
                    printf("SYN = |%d| star_name:|%s| dest_name:|%s| \ndata:|%s|\n", datapack.SYN, datapack.star_name, datapack.dest_name, datapack.data);

                    // 打印这个数据是从那个通信符号中读取到的
                    printf("<<<  events[i].data.fd =|%d|  star_name:|%s| dest_name:|%s|>>>", events[i].data.fd, datapack.star_name, datapack.dest_name);
                    int f = 0;
                    switch (datapack.SYN)
                    {
                    case 1: // 处理添加好友申请
                            // 去用户表找目标用户 看是否存在
                         memset( &dest_user , 0 ,sizeof(dest_user));
                        strcpy(dest_user.name, datapack.dest_name);
                        dest_user = find_friend_userinfo(dest_user);
                        if (dest_user.status == -1)
                        {
                            // 没有找到这个用户
                            strcpy(datapack.dest_name, datapack.star_name);
                            strcpy(datapack.star_name, "服务器");
                            strcpy(datapack.data, "没有找到");
                            datapack.SYN = 1;
                        }
                        else
                        {
                            
                            FriendList user_friend;
                            strcpy(user_friend.user_name , datapack.star_name );
                            //修改好友列表
                            strcpy(user_friend.firend , datapack.dest_name);
                            // 找到这个用户
                            if (fri_alter_userinfo(user_friend , peoplelist ))
                            {
                                strcpy(datapack.dest_name, datapack.star_name);
                                strcpy(datapack.star_name, "服务器");
                                strcpy(datapack.data, "添加成功");
                                datapack.SYN = 1;
                            }

                            
                        }

                        printf("%d\n%s\n%s\n%s\n" , datapack.SYN, datapack.star_name ,datapack.dest_name ,datapack.data);
                        if (-1 == send(events[i].data.fd, &datapack, sizeof(datapack), 0))
                        {
                            perror("send error");
                            ERRLOG(" 在 发送好友列表的时候出现错误  ");
                        }
                        printf("发送好友添加结果\n");

                        break;
                    case 2:// 发送好友列表
                        printf("成功收到好友列表申请\n");
                        /* 获取这个账号的全部好友名称 然后发送给客户端 */
                      
                        FriendList user_friend;
                        strcpy(user_friend.user_name , datapack.star_name);
                        user_friend = fri_find_userinfo( user_friend ,peoplelist);
                        printf("好友列表获取成功\n");
                        datapack.SYN = 2;
                        strcpy(datapack.star_name , "服务器");
                        strcpy(datapack.dest_name , user_friend.user_name);
                        sprintf( datapack.data , "%s"   ,user_friend.firend );
                        printf("%d\n%s\n%s\n%s\n" , datapack.SYN, datapack.star_name ,datapack.dest_name ,datapack.data);
                        if (-1 == send( events[i].data.fd, &datapack, sizeof(datapack), 0))
                        {
                            perror("send error");
                            ERRLOG(" 在 发送好友列表的时候出现错误  ");
                        }

                        printf("发送好友列表成功\n");

                        break;
                    case 3: // 处理找好友聊天
                 
                        for (size_t num = 0; num < ONLINE; num++)
                        {
                            if (events[i].data.fd == convert[num].star_fd) // 在k数组中 找到这个通信符号
                            {
                                strcpy(convert[num].star_name, datapack.star_name); // 将这个通信符号的起点名字设置为此次数据发送者的名字
                                printf("\n\n num = %ld  star_name =%s\n\n", num, convert[num].star_name);
                                strcpy(convert[num].dest_name, datapack.dest_name);

                                for (size_t z = 0; z < ONLINE; z++)
                                {
                                    if (strcmp(convert[z].star_name, datapack.dest_name) == 0)
                                    {
                                        convert[num].dest_fd = convert[z].star_fd;
                                        f = num;
                                    }
                                }
                            }
                        }
                        // 处理消息请求   进行消息转发
                        printf("\n");
                        printf(" ================= star_name=|%s|  dest_name=|%s|=================\n", datapack.star_name, datapack.dest_name);
                        printf("--------------------------------------------------\n");
                        printf("star_name:|%s| dest_name:|%s| \n star_fd=|%d|   dest_fd =|%d|\n", convert[f].star_name, convert[f].dest_name, convert[f].star_fd, convert[f].dest_fd);
                        printf("--------------------------------------------------\n");
                        printf("\n");
                        send(convert[f].dest_fd, &datapack, sizeof(datapack), 0);
                        break;
                    case 4:  // 处理好友间互传文件

                        break;
                    case 5 ://处理好友删除
                        memset( &dest_user , 0 ,sizeof(dest_user));
                        strcpy(dest_user.name, datapack.dest_name);
                        dest_user = find_friend_userinfo(dest_user);
                        if (dest_user.status == -1)
                        {
                            // 没有找到这个用户
                            strcpy(datapack.dest_name, datapack.star_name);
                            strcpy(datapack.star_name, "服务器");
                            strcpy(datapack.data, "这个账号不存在");
                            datapack.SYN = 5;
                        }
                        else
                        {
                            
                            FriendList user_friend;
                            strcpy(user_friend.user_name , datapack.star_name);
                            //修改好友列表
                            strcpy(user_friend.firend , datapack.dest_name);
                            // 找到这个用户
                            if (fri_del_userinfo(user_friend , peoplelist ))
                            {
                                strcpy(datapack.dest_name, datapack.star_name);
                                strcpy(datapack.star_name, "服务器");
                                strcpy(datapack.data, "删除成功");
                                datapack.SYN = 5;
                                ERRLOG("好友删除成功");
                            }
                           
                            
                        }
                        if (-1 == send(events[i].data.fd, &datapack, sizeof(datapack), 0))
                        {
                            perror("send error");
                            ERRLOG(" 在 发送好友列表的时候出现错误  ");
                        }
                        printf("发送好友添加结果\n");

                        break;
                    case 6 ://处理查找好友请求
                        memset( &dest_user , 0 ,sizeof(dest_user));
                        strcpy(dest_user.name, datapack.dest_name);
                        dest_user = find_friend_userinfo(dest_user);
                        if (dest_user.status == -1)
                        {
                            // 没有找到这个用户
                            strcpy(datapack.dest_name, datapack.star_name);
                            strcpy(datapack.star_name, "服务器");
                            strcpy(datapack.data, "没有找到");
                            datapack.SYN = 6;
                        }
                        else
                        {
                            
                         
                            strcpy(datapack.dest_name, datapack.star_name);
                            strcpy(datapack.star_name, "服务器");
                            strcpy(datapack.data, "查找成功");
                            datapack.SYN = 6;
                            
                        }
                        if (-1 == send(events[i].data.fd, &datapack, sizeof(datapack), 0))
                        {
                            perror("send error");
                            ERRLOG(" 在 发送好友列表的时候出现错误  ");
                        }
                        printf("发送查找好友结果\n");

                        break;
                    default:
                        break;
                    }
                }
            }
        }
    }

    close(server_fd);
    close(epoll_fd);
}

// pthread_mutex_t lock_TCP;


void friend_f_add_Print( FriendList user_data) 
{
   
    FILE *fp=fopen("my_file/friend_info.txt","a");
    if (NULL==fp)
    {
        printf("文件打开失败\n");
        return;
    }

    fseek(fp,0,SEEK_END);
    fprintf(fp, "姓名:%s|\t好友列表:%s\n", user_data.user_name,user_data.firend);
    fclose(fp);
    printf("\n-friend_f_add_Print 追加写入文件成功-------\n");

    friend_f_Scanf(peoplelist);
 

}


void friend_f_Scanf(friend_list* friend)
{
printf("\n-刷新好友列表-------\n");
    FILE *fp=fopen("my_file/friend_info.txt","r");
    if (NULL==fp)
    {
        printf("文件打开失败\n");
        return;
    }
    fseek(fp,0,SEEK_SET);
    FriendList user_data;
    int flag=0 ,star_my_name=0 ,   star_myfriend=0;
  
    char acc_data_temp[sizeof(user_data)];
    
    while (  fgets( acc_data_temp , sizeof(user_data)  , fp)  != NULL  )
    {
        flag=0 ;
        star_my_name=0 ; 
        star_myfriend=0;

        acc_data_temp[strlen(acc_data_temp)-1] = '\0';
        printf("acc_data_temp : |%s|\n",acc_data_temp);

        for (size_t i = 0; i < strlen(acc_data_temp); i++)
        {
            if ((acc_data_temp[i] == ':'  && flag == 0 )  || (acc_data_temp[i] == ':'  && flag == 2)   )
            {
                flag++;

                continue;
            }
            

            if ( flag == 1)
            {
                if (acc_data_temp[i] !='|' )
                {
                    user_data.user_name[star_my_name] =  acc_data_temp[i];
                    star_my_name++;
                }


                if (acc_data_temp[i] =='|' )
                {
                    user_data.user_name[star_my_name]='\0';
                    printf("user_data.user_name:|%s|\n",user_data.user_name);
                    flag++;
                }
                
              
       
            }

            if ( flag == 3)
            {
                user_data.firend[star_myfriend]  =  acc_data_temp[i];
                star_myfriend++;
            }
            
            
            
        }
        

        printf("姓名:|%s|\n好友列表:|%s|\n",user_data.user_name ,user_data.firend);
        //fri_pos_insert_LinkList( user_data , friend->len+1 ,friend);   //没进去
        printf("\n-刷新好友列表成功一次-------\n");
        memset(&user_data , 0 ,sizeof(user_data));
        memset(acc_data_temp , 0 , sizeof(acc_data_temp));
    }
    fclose(fp);
 

}
